<style lang="less">
    @import './index.less';
</style>

<template>
  <div>
    <Card dis-hover>
      <Row>
        <i-col span="20" class="margin-bottom-5">
          <div v-show="searchList">
            <Input placeholder="合同编号" size="small" style="width: 200px" v-model="contract_number"></Input>
            <Button class="margin-right-5" type="primary" size="small" icon="ios-search" @click="search">搜索</Button>
            <Button type="primary" size="small" icon="arrow-down-b" @click="searchControl">高级搜索</Button>
          </div>
          <div v-show="!searchList">
            <Input placeholder="合同编号" size="small" style="width: 200px" v-model="contract_number"></Input>
            <Select placeholder="客户名称" filterable clearable size="small" class="margin-right-5" style="width: 200px" v-model="customer_id">
              <Option v-for="item in companyList" :value="item.customer_id" :key="item.customer_id">{{item.customer_name}}</Option>
            </Select>
            <DatePicker type="daterange" ref="setDates" size="small" placeholder="回款时间范围"  @on-change="getDates" placement="bottom-end" style="width: 200px"></DatePicker>
            <Button class="margin-right-5" type="primary" size="small" icon="ios-search"  @click="search">搜索</Button>
            <Button type="primary" size="small" @click="searchControl" icon="arrow-up-b">收起</Button>
          </div>
        </i-col>
        <i-col span="4">
          <addBtn @addclick="createHandle" class="pull-right"></addBtn>
        </i-col>
      </Row>
      <Table :columns="tableColumns" :data="tableData.data"></Table>
      <Page :current="currentPage" :total="tableData.totalCount" :page-size="pageSize" show-total @on-change="changePage"></Page>
    </Card>
     <Modal v-model="modalControl" width="1200" 
        :loading="loading"
        :title="modalTitle"
        :ok-text = okText
        @on-ok="submit('modalRef')"
        @on-cancel="cancel('modalRef')">
      <Form :model="backpaymentInfo" ref="modalRef" :rules="ruleValidate" label-position="right" :label-width="110">
        <Row>
          <i-col span="8" offset="2">
            <FormItem label="客户名称" prop="customer_id">
              <Select v-model="backpaymentInfo.customer_id" transfer clearable filterable @on-change="getContracts" :disabled="isDisabled">
                <Option v-for="item in companyList" :key="item.contract_id" :value="item.customer_id">{{item.customer_name}}</Option>
              </Select>
            </FormItem>
          </i-col>
          <i-col span="8" offset="3">
            <FormItem label="合同编号" prop="contract_id">
              <Select v-model="backpaymentInfo.contract_id" transfer clearable filterable @on-change="getReceivables" not-found-text="empty" :disabled="isDisabled">
                <Option v-for="item in contractList" :key="item.contract_id" :value="item.contract_id">{{item.contract_number}}</Option>
              </Select>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="8" offset="2">
            <FormItem label="合同金额">
              <Input v-model="contractMoney" style="width:93%" disabled></Input>
              <span class="margin-left-3">元</span>
            </FormItem>
          </i-col>
          <i-col span="8" offset="3">
            <FormItem label="累计回款金额">
              <Input v-model="historyBankpaymentSum" style="width:93%" disabled></Input>
              <span class="margin-left-3">元</span>
            </FormItem>
          </i-col>
        </Row>
        <Row>
          <i-col span="8" offset="2">
            <FormItem label="本次回款总金额" prop="planBackpayment">
              <Input v-model="backpaymentInfo.planBackpayment" style="width:93%" :disabled="isDisabled"></Input>
              <span class="margin-left-3">元</span>
            </FormItem>
          </i-col>
          <i-col span="8" offset="3">
            <FormItem label="本次回款时间" prop="backpayment_date">
              <DatePicker v-model="backpaymentInfo.backpayment_date" type="date" ref="backpaymentDate" transfer placement="top-start" :disabled="isDisabled"></DatePicker>
            </FormItem>
          </i-col>
        </Row>
        <Collapse value="1">
            <Panel name="1">
                对应期次
                <!-- 添加 -->
              <can-edit-table 
                  slot="content"
                  v-model="receivables"
                  v-show="backpaymentInfo.receivablebackpayments.length === 0"
                  @on-cell-change="handleCellChange" 
                  :editIncell="editIncell" 
                  :columns-list="modalColumns"
              ></can-edit-table>
                <!-- 修改 -->
              <can-edit-table 
                  slot="content"
                  v-show="backpaymentInfo.receivablebackpayments.length !== 0"
                  v-model="backpaymentInfo.receivablebackpayments"
                  @on-cell-change="handleCellChange" 
                  :editIncell="editIncell" 
                  :columns-list="modalColumns"
              ></can-edit-table>
              <Row slot="content" class="margin-top-10">
                <i-col span="3" offset="21">
                  <h3>总计：{{totalSum}} 元</h3>
                </i-col>
              </Row>
            </Panel>
        </Collapse>
      </Form>
    </Modal>
  </div>
</template>

<script>
import moment from 'moment';
import deleteBtn from './component/access-delete-button.vue';
import modifyBtn from './component/access-modify-button.vue';
import addBtn from './component/access-add-button.vue';
import checkBtn from './component/access-check-button.vue';
import canEditTable from './component/canEditTable.vue';


export default {
  data() {
    var valideNumber = (rule, value, callback) => {
        if(!Number.isInteger(+value)) {
           callback(new Error('请输入数字值'));
        }else {
          callback()
        }
    };
    return {
      searchList:true,
      loading:true,
      modalControl:false,
      isDisabled:false,
      editIncell:true,
      modalTitle:'',
      okText:'',
      // 分页参数
      contract_number:'',
      customer_id:'',
      start:'',
      end:'',
      currentPage:1,
      pageSize:15,
      ruleValidate:{
        customer_id:[{ required: true, message: '请选择客户名称', trigger: 'blur' }],
        contract_id:[{ required: true, message: '请选择合同编号', trigger: 'blur' }],
        backpayment_date:[{type:'date', required: true, message: '请选择实际回款时间', trigger: 'blur' }],
        planBackpayment:[{required: true, message: '请填写本次回款总金额', trigger: 'blur'},{ validator: valideNumber , trigger: 'change'}]
      },
      tableColumns:[
        {
          title:'回款日期',
          align:'center',
          key:'backpayment_date'
        },{
          title:'本次回款金额(元)',
          align:'center',
          key:'backpayment_amount'
        },{
          title:'对应客户',
          align:'center',
          key:'customer_name'
        },{
          title:'合同编号',
          align:'center',
          key:'contract_number'
        },{
          title:'合同负责人',
          align:'center',
          key:'responsible_name'
        },{
          title:'所在部门',
          align:'center',
          key:'org_name'
        },{
          title:'录入人员',
          align:'center',
          key:'creator'
        },{
          title:'复核状态',
          align:'center',
          render:(h,params) => {
            if(params.row.status === '未复核') {
              return h('span',{
                style:{
                  color:'#ed3f14'
                }
              },params.row.status)
            }else {
              return h('span',{},params.row.status)
            }
          }
        },{
          title: '操作',
          align: 'center',
          width:'140',
          render: (h, params) => {
              return h('div', [
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '查看'
                  }
                }, [h('Button', {
                  props: {
                    size: 'small',
                    icon: 'qr-scanner',
                    type: 'text'
                  },
                  on: {
                    click: () => {
                      this.$router.push({
                        name:'fi_income-record-mgt-detail',
                        params:{id:params.row.backpayment_id}
                      })
                    }
                  }
                })]),
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '复核',
                  }
                }, [h(checkBtn, {
                  props:{
                    status:params.row.status,
                    creator:params.row.creator
                  },
                  on: {
                    checkClick: () => {
                      this.checkHandle(params.row.backpayment_id);
                    }
                  }
                }
                )]),
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '编辑',
                  }
                }, [h(modifyBtn, {
                  props:{
                    status:params.row.status,
                    creator:params.row.creator
                  },
                  on: {
                    modifyClick: () => {
                      this.modifyHandle(params.row.backpayment_id);
                    }
                  }
                }
                )]),
                h('Tooltip', {
                  props: {
                    placement: 'top',
                    content: '删除'
                  }
                }, [h(deleteBtn, {
                  props:{
                    status:params.row.status,
                    creator:params.row.creator
                  },
                  on: {
                    delClick: () => {
                      this.$Modal.confirm({
                        title: '确认',
                        content: '确认要删除这条记录吗？',
                        onOk: () => {
                          this.deleteHandle(params.row.backpayment_id);
                        }
                      });
                    }
                  }
                })])
              ]);
            }
        }
      ],
      modalColumns:[
        {
          title:'期次',
          key:'count',
          align:'center',
        },{
          title:'应收约定回款日期',
          key:'receivable_date',
          align:'center',
        },{
          title:'应收金额(元)',
          key:'receivable_amount',
          align:'center'
        },{
          title:'已回款金额(元)',
          align:'center',
          key:'backpaymentSum'
        },{
          title:'未回款金额(元)',
          align:'center',
          key:'backpaymentSub'
        },{
          title:'本次回款金额(元)',
          algin:'center',
          key:'amount',
          align:'center',
          editable: true
        }
      ],
      tableData:{},
      backpaymentInfo:{
        planBackpayment:'0',
        receivablebackpayments:[],
        status:'未复核',
      },
      companyList:[],
      contractList:[],
      receivables:[],
      historyBankpaymentSum:0, // 该合同累计回款金额
      contractMoney:0, // 该合同签订金额
      totalSum:0, // 应收总和
      userName:''
    }
  },
  methods:{
    // tableData
    getBackpayments() {
      this.$http.get('/fi/backpayments/page?contract_number='+this.contract_number+'&customer_id='+this.customer_id+'&start='+this.start+'&end='+this.end+'&currenPage='+this.currentPage+'&pageSize='+this.pageSize).then((res) => {
        this.tableData = res.data.returnValue
      })
    },
    // 公司
    getCompanys() {
      this.$http.get('/fi/customer/customers').then((res) => {
        this.companyList = res.data.returnValue
      })
    },
    // 公司下的合同
    getContracts(value) {
      this.$http.get('/fi/contracts?like=&customer_id=' + value + '&org_id=&responsible=&status=执行中').then((res) => {
        this.contractList = res.data.returnValue
      })
    },
    // 合同下的应收期次
    getReceivables(value) {
      this.$http.get('/fi/contracts/' + value).then((res) => {
          this.historyBankpaymentSum = 0 
          this.contractMoney = res.data.returnValue.contract_amount // 合同总金额  
          this.receivables = res.data.returnValue.receivables
          // 添加
          _.map(this.receivables,(item,index) => {
              item['backpaymentSum'] = 0
              _.forEach(item.receivableBackpayments,i => {
                item['backpaymentSum'] = item['backpaymentSum'] + i.amount
              })
              item.backpaymentSub = item.receivable_amount - item.backpaymentSum
              this.historyBankpaymentSum = this.historyBankpaymentSum + item.backpaymentSum // 合同累计总回款金额
              item.amount = 0 // 设置本次回款金额为当前为回款金额
              return item
          })
          // 修改
          _.forEach(this.backpaymentInfo.receivablebackpayments,item => {
            // 遍历添加两个key，默认value为0
            this.$set(item,'backpaymentSum',0)
            this.$set(item,'backpaymentSub',item.receivable_amount) 
            let arr = this.receivables[_.findIndex(this.receivables,{receivable_id:item.receivable_id})].receivableBackpayments
            // 如果该条合同没有复核过，那么arr为空数组
            // 否则为复核过的历史
              _.forEach(arr,a => {
                item['backpaymentSum'] = item['backpaymentSum'] + a.amount
                item['backpaymentSub'] = item.receivable_amount - item['backpaymentSum']
              })
          })
      })
    },
    // 搜索时间
    getDates(date) {
      this.start = date[0]
      typeof(date[1]) != "undefined" ? this.end = date[1]:this.end = ''
    },
    // 搜索
    search() {
      this.getBackpayments() 
    },
    searchControl() {
      this.searchList = !this.searchList
      this.start = ''
      this.end = ''
      this.contract_number = ''
      this.customer_id = ''
      this.$refs['setDates'].handleClear()
      this.getBackpayments()
    },
    // 翻页
    changePage(page) {
      this.currenPage = page
      this.getBackpayments()
    },
    // 合同详情
    getBackpaymentInfo(id) {
      this.totalSum = 0
      this.$http.get('/fi/backpayments/' + id).then((res) => {
        this.backpaymentInfo = res.data.returnValue
        _.forEach(this.backpaymentInfo.receivablebackpayments,item => {
          this.totalSum = this.totalSum + item.amount
          this.backpaymentInfo.planBackpayment =this.totalSum.toString()
        })
      })
    },
    createHandle(name) {
      this.getCompanys()
      this.modalControl = true
      this.editIncell = true
      this.okText = '确定'
      this.modalTitle = "添加回款记录"
    },
    modifyHandle(id) {
      this.getCompanys()
      this.getContracts()
      this.getBackpaymentInfo(id)
      this.modalControl = true
      this.editIncell = true
      this.okText = '保存'
      this.modalTitle = '修改回款信息'
    },
    checkHandle(id) {
      this.getCompanys()
      this.getContracts()
      this.getBackpaymentInfo(id)
      this.modalControl = true
      this.editIncell = false
      this.isDisabled = true
      this.okText = '通过复核'
      this.modalTitle = '复核回款信息'
    },
    cancel(name) {
      this.cleanParmas(name)
    },
    submit(name) {
      this.$refs[name].validate((valid) => {
        if(valid) {
          if(this.totalSum === parseFloat(this.backpaymentInfo.planBackpayment)) {
            delete this.backpaymentInfo.customer_id
            delete this.backpaymentInfo.planBackpayment
            this.backpaymentInfo.backpayment_date = moment(this.backpaymentInfo.backpayment_date).format('YYYY-MM-DD')
            // 根据业务主键ID去判读实际业务需求
            // 新建
            if(!this.backpaymentInfo.backpayment_id) {
              _.forEach(this.receivables,(item,index) => {
                this.backpaymentInfo.receivablebackpayments.push({})
                this.backpaymentInfo.receivablebackpayments[index].receivable_id = item.receivable_id
                this.backpaymentInfo.receivablebackpayments[index].amount = item.amount
              })
              this.$http.post('/fi/backpayments',this.backpaymentInfo).then((res) => {
                this.$Message.success(res.data.message)
                this.modalControl = false
                this.cleanParmas('modalRef')
                this.getBackpayments()
              }).catch(() => {
                this.reloading()
                this.$Message.error('添加失败，请稍后重试。')
              })
            // 修改
            }else if(this.backpaymentInfo.backpayment_id && this.modalTitle == '修改回款信息'){
              this.$http.put('/fi/backpayments',this.backpaymentInfo).then((res) => {
                this.$Message.success(res.data.message)
                this.getBackpayments()
                this.modalControl = false
              }).catch(() => {
                this.reloading()
                this.$Message.error('修改失败，请重试！')
              })
            // 复核
            }else if(this.backpaymentInfo.backpayment_id && this.modalTitle === '复核回款信息') {
              var body = {
                backpayment_ids:[this.backpaymentInfo.backpayment_id],
                status:'已复核'
              }
              this.$http.put('/fi/backpayments/status',body).then((res) => {
                this.$Message.success('回款记录已复核')
                this.modalControl = false
                this.getBackpayments()
              }).catch(() => {
                this.$Message.error('回款记录复核失败，请稍后重试')
              })
            }
          }else {
            this.reloading()
            this.$Message.info('本次回款总金额与每期累计回款金额不相等，请确认回款金额')
          }
        }else{
          this.reloading()
        }
      })
    },
    reloading() {
        this.loading = false
        this.$nextTick(() => {
          this.loading = true
        })
    },
    cleanParmas(name) {
      this.totalSum = 0
      this.bankpaymentMoney = 0
      this.contractMoney = 0
      this.backpaymentInfo = {
        planBackpayment: 0,
        receivablebackpayments:[],
        status:'未复核',
      }
      this.receivables = []
      this.$refs['backpaymentDate'].handleClear() // 清空datepicker
      this.$refs[name].resetFields() // 清空表单验证提示
    },
    deleteHandle(id) {
      this.$http.delete('/fi/backpayments/' + id).then((res) => {
        this.$Message.info('删除成功')
        this.getBackpayments()
      }).catch(() => {
        this.$Message.error('删除失败，请重试')
      })
    },
    handleCellChange (val, index, key) {
      this.totalSum = 0 
      _.forEach(val,item => {
        this.totalSum = this.totalSum + item.amount
      })
    },
  },
  components: {
    deleteBtn,
    modifyBtn,
    addBtn,
    checkBtn,
    canEditTable
  },
  mounted() {  
    this.getBackpayments()
    this.getCompanys()
    this.userName = this.$auth.user().name
  }
}
</script>
